<template>
    <el-card shadow="hover" class="management-card">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="模板名称">
                <el-input v-model="searchForm.templateName" placeholder="请输入模板名称" clearable />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="header-actions">
            <el-upload action="http://localhost:5000/api/admin/resumes/uploadTemplate" :show-file-list="false"
                :before-upload="beforeUpload" :on-success="handleSuccess">
                <el-button type="primary">
                    <el-icon class="el-icon--left">
                        <Plus />
                    </el-icon>
                    上传新模板
                </el-button>
            </el-upload>
        </div>

        <!-- 数据表格 -->
        <el-table :data="templates" border stripe highlight-current-row style="width: 100%"
            header-row-class-name="custom-header">
            <el-table-column prop="templateName" label="模板名称" width="220" />
            <el-table-column prop="filePath" label="存储路径" show-overflow-tooltip />
            <el-table-column prop="uploadTime" label="上传时间" width="247" />
            <el-table-column label="状态" width="120">
                <template #default="{ row }">
                    <el-tag :type="row.status === '已禁用' ? 'warning' : 'success'" effect="dark">
                        {{ row.status === '已禁用' ? '已禁用' : '已启用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
                <template #default="{ row }">
                    <div class="action-buttons">
                        <el-button type="primary" size="small" plain @click="downloadTemplate(row)">
                            <el-icon>
                                <Download />
                            </el-icon>
                        </el-button>
                        <el-button type="danger" size="small" plain @click="deleteTemplate(row.id)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                        <el-button :type="row.status === '已禁用' ? 'success' : 'warning'" size="small" plain
                            @click="toggleStatus(row)">
                            {{ row.status === '已禁用' ? '启用' : '禁用' }}
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size="pageSize"
                :current-page="currentPage" @current-change="handlePageChange" @size-change="handleSizeChange" />
        </div>
    </el-card>
</template>

<script setup>
import { Plus, Download, Delete } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { get } from '@/request/request.js'

// 数据相关
const templates = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const currentResumeTemplate = ref({
    id: null,
    templateName: '',
    filePath: '',
    uploadTime: null,
    status: ''
})
const currentFilename = ref('')

// 搜索表单数据
const searchForm = ref({
    templateName: ''
})

// 获取数据
const fetchTemplates = async (page = 1) => {
    try {
        const params = {
            ...searchForm.value,
            page: page,
            size: pageSize.value
        }
        const res = await get('/api/admin/resumes/templates', params)
        console.log(res);
        
        templates.value = res.data.list
        total.value = res.data.total
    } catch (error) {
        ElMessage.error('获取模板失败')
    }
}

// 搜索处理
const handleSearch = () => {
    currentPage.value = 1
    fetchTemplates()
}

// 重置搜索
const handleReset = () => {
    searchForm.value = { templateName: '' }
    handleSearch()
}

// 状态切换
const toggleStatus = async (row) => {
    try {
        const newStatus = row.status === '已启用' ? '已禁用' : '已启用'
        currentResumeTemplate.value = { ...row }
        const templateData = { ...currentResumeTemplate.value }
        templateData.status = newStatus
        await get('/api/admin/resumes/updateTemplate', templateData)
        row.status = newStatus
        fetchTemplates(currentPage.value)
        ElMessage.success('状态更新成功')
    } catch (error) {
        ElMessage.error('状态更新失败')
    }
}

// 文件上传处理
const beforeUpload = (file) => {
    console.log(file)
    currentFilename.value = file.name
    const isAcceptType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
    if (!isAcceptType) {
        ElMessage.error('仅支持 PDF 和 Word 文档')
        return false
    }
    return true
}

const handleSuccess = (res) => {
    console.log(res.data)
    const templateData = { ...currentResumeTemplate.value }
    templateData.filePath = res.data
    templateData.templateName = currentFilename.value
    get('/api/admin/resumes/addTemplate', templateData)
    if (res.code === 200) {
        ElMessage.success('上传成功')
        fetchTemplates(currentPage.value)
    }
    fetchTemplates(currentPage.value)
}

// 分页处理
const handlePageChange = (page) => {
    currentPage.value = page
    fetchTemplates(page)
}

const handleSizeChange = (size) => {
    pageSize.value = size
    fetchTemplates()
}

//下载模板
const downloadTemplate = async (row) => {
    const filePath = row.filePath // 获取文件路径
    if (!filePath) {
        ElMessage.warning('文件路径无效')
        return
    }

    // 创建一个隐藏的 <a> 元素
    const link = document.createElement('a')
    link.href = filePath // 设置下载链接
    link.download = row.templateName || 'template' // 设置下载文件名
    document.body.appendChild(link) // 将 <a> 元素添加到 DOM 中
    link.click() // 触发点击事件
    document.body.removeChild(link) // 移除 <a> 元素
}

//删除模板
const deleteTemplate = async (id) => {
    try {
        await get(`/api/admin/deleteTemplate/${id}`)
        ElMessage.success('删除成功')
        fetchTemplates(currentPage.value)
    } catch (error) {
        ElMessage.error('删除成功')
    }
}

onMounted(() => {
    fetchTemplates()
})
</script>

<style lang="scss" scoped>
.management-card {
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    :deep(.el-card__header) {
        border-bottom: 1px solid #ebeef5;
        padding: 16px 20px;
    }

    .search-form {
        width: 80%;
        margin-bottom: 0px;

        .el-form-item {
            margin-right: 40px;
            margin-bottom: 0px;
        }
    }

    .header-actions {
        width: 19%;
        float: right;
        margin-bottom: 0px;
        display: flex;
        justify-content: flex-end;
    }

    .action-buttons {
        display: flex;
        gap: 8px;
        justify-content: center;
    }

    .pagination-wrapper {
        margin-top: 24px;
        display: flex;
        justify-content: flex-end;
    }
}

:deep(.el-table) {
    .el-table__cell {
        padding: 12px 0;
    }

    .custom-header th {
        background-color: #f8f9fc;
        font-weight: 600;
    }
}
</style>